﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UnityScriptEngine;

using System.Drawing.Printing;

namespace EnrollmentSystem
{
    public partial class frmEnrollmentReport : Form
    {

        UnityProcessor proc = new UnityProcessor();
        UnityScript[] dat = new UnityScript[0];
        Threader t = new Threader();
        UnityScript[] eudat = new UnityScript[0]; 
        
        DataTable items = new DataTable();
        DataTable itemsDetail = new DataTable();

        DataTable enrollment = new DataTable();
        DataTable grades = new DataTable();
        DataTable studentprofile = new DataTable();
        DataTable subject = new DataTable();

        public frmEnrollmentReport()
        {
            InitializeComponent();
            InitializeFrameSliderForm();
        }

        private void InitializeForm()
        {

            InitializeItemTable();
            btnPrint.Click +=new EventHandler(btnPrint_Click);
            proc.ProcessCompleted += new ProcessHandler(proc_ProcessCompleted);
            proc.ProcessError += new ProcessHandler(proc_ProcessError);
            btnSearch.Click += new EventHandler(btnSearch_Click);
            InitialData();
        }

        void btnSearch_Click(object sender, EventArgs e)
        {
            pnlMsg.Visible = true;
            LoadSearchData();
        }

        void proc_ProcessError(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                MessageBox.Show(desc);
                pnlMsg.Visible = false;
            });
        }

        void proc_ProcessCompleted(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                switch (id)
                {
                    case "LOADSEARCH":
                        
                        proc.DBPUX_Data_Fetch(out eudat);
                        studentprofile = eudat[0].ToDataTable();
                        enrollment = eudat[1].ToDataTable();
                        grades = eudat[2].ToDataTable();
                        
                        
                        items.Rows.Clear();
                        itemsDetail.Rows.Clear();
                        ConstructItems();
                        grdItems.DataSource = items;

                        for (int i = 0; i < grdItems.Columns.Count; i++)
                            grdItems.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;

                            pnlMsg.Visible = false;
                        break;
                    case "LOAD":
                        UnityScript[] edat;
                        proc.DBPUX_Data_Fetch(out edat);
                        
                        lstAYsem.Items.Clear();
                        if (edat[0].Data_Count > 0)
                        {
                            lstAYsem.Items.AddRange(edat[0].ToList<string>(0));
                            //lstAYsem.Items.Add("All");
                            lstAYsem.SelectedIndex = 0;

                            lstCourse.Items.Clear();
                            lstCourse.Items.AddRange(edat[1].ToList<string>(0));
                            lstCourse.SelectedIndex = 0;

                            lstYear.Items.Clear();
                            lstYear.Items.AddRange(edat[2].ToList<string>(0));
                            lstYear.SelectedIndex = 0;
                        }

                        
                        break;
                }
            });
        }

        void FormatGrid()
        {
            grdItems.Columns[0].Width = (grdItems.Width * 19) / 100;
            grdItems.Columns[1].Width = (grdItems.Width * 19) / 100;
            grdItems.Columns[2].Width = (grdItems.Width * 19) / 100;
            grdItems.Columns[3].Width = (grdItems.Width * 20) / 100;
            grdItems.Columns[4].Width = (grdItems.Width * 20) / 100;
           

            grdItems.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            grdItems.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            grdItems.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdItems.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdItems.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
           
            lblStatus.Text = grdItems.Rows.Count + " Records";
            grdItems.Sort(grdItems.Columns[0], ListSortDirection.Ascending);

        }

        void InitializeItemTable()
        {
            items.Columns.Add("ID Number");
            items.Columns.Add("Student Name");
            items.Columns.Add("Course");
            items.Columns.Add("Subject Code");
            items.Columns.Add("Unit(s)");
            items.Columns.Add("Grade");

            grdItems.DataSource = items;

            grdItems.Columns[1].DefaultCellStyle.WrapMode = DataGridViewTriState.True;

            grdItems.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdItems.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdItems.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            
            grdItems.Columns[5].DefaultCellStyle.Format = "#,#0.00";

        }
        void InitialData()
        {
            while (proc.IsRunning)
            {
                System.Threading.Thread.Sleep(1);
            }
            proc.ProcStart();
            UnityScript x = new UnityScript("LOAD", 4);
            x.Script_Add(Script.DBPUX_BEGIN);
            x.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT DISTINCT fSchoolYear FROM tblEnrollment"));
            x.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT fID, fData, fStamp FROM tblLookUp WHERE fKey = 'COURSES_OFFERED'"));
            x.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT fID, fData, fStamp FROM tblLookUp WHERE fKey = 'YEAR_LEVEL'"));
            x.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(x);
        }
        void LoadSearchData()
        {
            
            UnityScript U = new UnityScript("LOADSEARCH", 4);
            U.Script_Add(Script.DBPUX_BEGIN);
            U.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT * FROM tblstudentprofile"));
            
            U.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT fID, t1.fEnrollmentNumber, t1.fStudentNumber, ffName, ffCourse, fYearLevel, fStamp FROM tblEnrollment t1, " +
                    " (SELECT fNumber, fName AS ffName, fCourse AS ffCourse FROM tblstudentprofile t22 WHERE fCourse = '{1}' ORDER BY fName ASC) AS t2 " +
                    "WHERE (t1.fStudentNumber = t2.fNumber) AND (fSchoolYear = '{0}' AND fYearLevel = '{2}')", lstAYsem.Text, lstCourse.Text, lstYear.Text));
            
            U.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT fID, fEnrollmentNum, fSubjectCode, ffSubjectName, fGrade, fUnits, fStamp FROM tblgrades t1, " +
                    " (SELECT fID AS ffID, fCode AS ffSubjectName FROM tblsubjectplanner t22) As t2 " +
                    " WHERE (fSubjectCode = ffID) "));
           
            U.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(U);
        }

        struct eReport
        {
            public string name;
            public string id;
            public string course;
            public string[] subject;
            public int[] unit;
            public float[] grade;

        }
        void ConstructItems()
        {
         
                for (int i = 0; i < enrollment.Rows.Count; i++)
                {
                    string eNumber = enrollment.Rows[i]["fEnrollmentNumber"].ToString();

                    for (int j = 0; j < grades.Rows.Count; j++)
                    {
                        string eNumber2 = grades.Rows[j]["fEnrollmentNum"].ToString();
                        if (eNumber.Equals(eNumber2))
                        {
                            DataRow dr = items.NewRow();
                            dr[0] = enrollment.Rows[i]["fStudentNumber"].ToString();
                            dr[1] = enrollment.Rows[i][2].ToString();
                            dr[2] = enrollment.Rows[i][3].ToString();

                            string subjCode = grades.Rows[j][2].ToString();
                            dr[3] = subjCode;
                            dr[4] = grades.Rows[j][4].ToString();
                            dr[5] = grades.Rows[j][3].ToString();
                            items.Rows.Add(dr);
                        }
                    }
                }
             
           
        }
        
        //printing
        int cnt = 0;
        int pp = 1;
        void btnPrint_Click(object sender, EventArgs e)
        {
            PrintDocument pd = new PrintDocument();
            pd.DocumentName = lblText.Text;
            pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
            PrintDialog pdlg = new PrintDialog();
            pdlg.Document = pd;
            if (pdlg.ShowDialog() == DialogResult.OK)
            {
                PrintPreviewDialog ppdlg = new PrintPreviewDialog();
                ppdlg.Document = pd;
                pp = 1;
                //Tracking.EnterLog("Price Table is printed.", DateTime.Now.ToString());
                ppdlg.ShowDialog();
            }
        }

        void pd_PrintPage(object sender, PrintPageEventArgs e)
        {
            float lpp = 0;
            float y = 0;
            float tm = e.MarginBounds.Top;
            float lm = e.MarginBounds.Left - 50;
            float rm = e.PageBounds.Width - 50;
            float bm = e.PageBounds.Height - 100;
            float ht = 0;
            Font cFont;
            StringFormat sf = new StringFormat();


            //Header
            y = 110;
            cFont = new Font("Courier New", 11f, FontStyle.Bold);
            ht = cFont.GetHeight(e.Graphics);
            sf.Alignment = StringAlignment.Center;
            e.Graphics.DrawString("ENROLLMENT REPORT", new Font("Courier New", 17f, FontStyle.Bold), Brushes.Black, e.PageBounds.Width / 2, 50, sf);
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y - (ht / 2)), new PointF(rm, y - (ht / 2)));
            
            sf.Alignment = StringAlignment.Near;
            e.Graphics.DrawString("School: Golden West Colleges", cFont, Brushes.Black, lm, y, sf);
            sf.Alignment = StringAlignment.Far;
            e.Graphics.DrawString(DateTime.Now.ToString(), cFont, Brushes.Black, rm, y, sf);
            y += ht;
            sf.Alignment = StringAlignment.Near;
            e.Graphics.DrawString("Address: Alaminos City, Pangasinan", cFont, Brushes.Black, lm, y, sf);
            y += ht;
            e.Graphics.DrawString("Telephone Number: (075) 552 - 7382", cFont, Brushes.Black, lm, y, sf);
            y += ht;
            e.Graphics.DrawString("Course: "+lstCourse.Text, cFont, Brushes.Black, lm, y, sf);
            y += ht;
            e.Graphics.DrawString("Year Level: " + lstYear.Text, cFont, Brushes.Black, lm, y, sf);
            y += ht;
            e.Graphics.DrawString("Page Number: "+pp, cFont, Brushes.Black, lm, y, sf);
            //Column Header
            y += ht;
            y += ht;
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y - (ht / 2)), new PointF(rm, y - (ht / 2)));

            e.Graphics.DrawString("Student Name", cFont, Brushes.Black, lm + 4, y, new StringFormat());
            if(chkdetail.Checked == false)
                e.Graphics.DrawString("Subjects and Units", cFont, Brushes.Black, lm + 300, y, new StringFormat());
            else
                e.Graphics.DrawString("Subjects, Units and Grades", cFont, Brushes.Black, lm + 300, y, new StringFormat());

            
            //Data
            y += ht * (1.5f);
            cFont = new Font("Courier New", 10f, FontStyle.Regular);
            ht = cFont.GetHeight(e.Graphics);
            lpp = (bm - y) / ht;
            int cl = 0;
            string name = "";
            int x = 1;
            while (cl <= lpp && cnt < grdItems.Rows.Count)
            {
                
                string str = grdItems.Rows[cnt].Cells[1].Value.ToString();
                if (!name.Equals(str))
                {
                    e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y - (ht / 2)), new PointF(rm, y - (ht / 2)));
                    e.Graphics.DrawString((x) + "." + str, cFont, Brushes.Black, lm + 4, y, sf);
                    name = grdItems.Rows[cnt].Cells[1].Value.ToString();
                    x++;
                }

                str = grdItems.Rows[cnt].Cells[3].Value.ToString();
                e.Graphics.DrawString("" + str, cFont, Brushes.Black, lm + 250, y, sf);

                str = grdItems.Rows[cnt].Cells[4].Value.ToString();
                e.Graphics.DrawString("" + str, cFont, Brushes.Black, lm + 650, y, sf);

                if (chkdetail.Checked == true)
                {
                    str = grdItems.Rows[cnt].Cells[5].Value.ToString();
                    e.Graphics.DrawString("" + str, cFont, Brushes.Black, lm + 720, y, sf);
                }
                y += ht * (1.25f);
                cnt++;
                cl++;
            }
            //e.Graphics.DrawString("Total", cFont, Brushes.Blue, stx - 150, y + 10, sf);
            //e.Graphics.DrawString(, cFont, Brushes.Blue, stx - 4, y + 10, sf);

            if (cnt < grdItems.Rows.Count)
            {
                e.HasMorePages = true;
                pp++;
            }
            else
            {
                y += ht;
                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y - (ht / 2)), new PointF(rm, y - (ht / 2)));
                e.Graphics.DrawString("******************** Nothing Follows ********************", cFont, Brushes.Black, lm + 150, y + ht, new StringFormat());

                pp = 1;
                e.HasMorePages = false;
                cnt = 0;
            }
        }

        
    }
}
